package com.tyun.common.oauth2;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.tyun.modules.sys.entity.SysUser;
import com.tyun.modules.sys.entity.SysUserToken;
import com.tyun.modules.sys.service.ISysUserService;
import com.tyun.modules.sys.service.ISysUserTokenService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @author tao cong cong
 * @create 2017/12/24 下午4:05
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Autowired
    private ISysUserTokenService sysUserTokenService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 将token类型转为OAuth2Token
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
        // 角色
        Set<String> roleSet = new HashSet<>();
        roleSet.add("admin");
        // 菜单权限
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        Set<String> permsSet = sysUserService.queryUserMenuPermsList(sysUser.getUserid());
        info.setRoles(roleSet);
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();

        SysUserToken sysUserToken = new SysUserToken();
        //根据accessToken，查询用户信息
        SysUserToken tokenEntity = sysUserTokenService.selectOne(new EntityWrapper<SysUserToken>(sysUserToken).eq("token",accessToken));
        //token失效
        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }

        //查询用户信息
        SysUser user = sysUserService.selectById(tokenEntity.getUserId());
        //账号锁定
        /*if(user.getStatus() == 0){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }*/

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, getName());
        return info;
    }
}
